package com.noble.glamour.ui.discover;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;

import com.noble.glamour.R;
import com.noble.glamour.bean.center.user.light.UserInfoLightweight;
import com.noble.glamour.bean.center.user.light.UserLight;
import com.noble.glamour.bean.center.user.light.UserLightList;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.baseui.BaseFragment;
import com.noble.glamour.module.logic.baseui.LoadingDialog;
import com.noble.glamour.module.logic.baseui.custom.CustomStatusListView;
import com.noble.glamour.module.logic.baseui.xlistview.ExListView;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.glamour.module.util.UIShow;
import com.noble.library.log.PToast;
import com.noble.library.observe.MsgMgr;
import com.noble.library.observe.MsgType;
import com.noble.library.observe.PObserver;
import com.noble.library.utils.ViewUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 发现
 * Created by zhang on 2017/4/20.
 */
public class DiscoverFragment extends BaseFragment implements RequestComplete, View.OnClickListener, PObserver, ExListView.IXListViewListener {
    private static final int Group_sayHai_Msg = 100; //群打招呼

    private CustomStatusListView customStatusListView;
    private ExListView exListView;
    private Button groupSayhiBtn;

    private DiscoverAdapter adapter;
    private List<UserLight> infos = new ArrayList<>();

    private int page = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.discover_fragment);
        initView();
        onRefresh(); //默认加载全部
        MsgMgr.getInstance().attach(this);
        return getContentView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MsgMgr.getInstance().detach(this);
    }

    private void initView() {
        groupSayhiBtn = (Button) findViewById(R.id.discover_group_sayhi_btn);
        groupSayhiBtn.setOnClickListener(this);
        groupSayhiBtn.setVisibility(ModuleMgr.getCenterMgr().getMyInfo().isMan() ? View.VISIBLE : View.GONE);
        setGroupSayhiBtn(false);

        customStatusListView = (CustomStatusListView) findViewById(R.id.discover_content);

        //@updateAuthor Mr.Huang
        //@updateDate 2017-07-26
        View mViewTop;
        if (ModuleMgr.getCenterMgr().getMyInfo().isMan()) {
            FrameLayout layout = new FrameLayout(getContext());
            layout.setBackgroundColor(getContext().getResources().getColor(R.color.bg_color));
            layout.setLayoutParams(new ExListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            layout.setPadding(0, ViewUtils.dpToPx(5), 0, 0);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.abtest_search_label, layout, false);
            layout.addView(view);
            mViewTop = layout;
        } else {
            //如果是女号隐藏搜索
            mViewTop = LayoutInflater.from(getContext()).inflate(R.layout.layout_margintop, null);
        }

        exListView = customStatusListView.getExListView();
        exListView.setXListViewListener(this);
        exListView.setPullRefreshEnable(true);
        exListView.setPullLoadEnable(true);
        exListView.addHeaderView(mViewTop);
        adapter = new DiscoverAdapter(getActivity(), infos);
        exListView.setAdapter(adapter);
        exListView.setHeaderStr(null, null);
        exListView.setHeaderHintType(2);
        customStatusListView.showLoading();
    }

    @Override
    public void onRefresh() {
        exListView.setPullRefreshEnable(true);
        exListView.setPullLoadEnable(true);
        page = 1;
        ModuleMgr.getCommonMgr().reqRecommednList(1, this);
    }

    @Override
    public void onLoadMore() {
        page++;
        ModuleMgr.getCommonMgr().reqRecommednList(1, this);
    }

    @Override
    public void onRequestComplete(HttpResponse response) {
        exListView.stopRefresh();
        exListView.stopLoadMore();
        if (response.getUrlParam() == UrlParam.reqRecommednList) {
            setMainData(response);
        }
    }

    private void setMainData(HttpResponse response) {
        if (response.isOk()) {
            if (!response.isCache()) {
                UserLightList list = (UserLightList) response.getBaseData();
                if (list.getLightList().size() != 0) {

                    //ref 如果是 true 并且请求的如果非第一页
                    //那么返回来的就是第一页 应该把之前的数据都清掉，把返回的数据作为第一页
                    if (page == 1) {
                        if (infos.size() != 0) {
                            infos.clear();
                        }
                        page = 1;
                    }

                    infos.addAll(list.getLightList());
                    if (infos.size() < 10) {
                        exListView.setPullLoadEnable(false);
                    } else {
                        exListView.setPullLoadEnable(true);
                    }
                    adapter.notifyDataSetChanged();
                    customStatusListView.showExListView();
                } else {
                    if (page == 1) {
                        customStatusListView.showNoData("暂无数据", "重试", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                customStatusListView.showLoading();
                                onRefresh();
                            }
                        });
                    } else {
                        exListView.setPullLoadEnable(false);
                    }
                }
            } else {
                if (page == 1) {
                    UserLightList list = (UserLightList) response.getBaseData();
                    if (list != null && list.getLightList().size() != 0) {
                        if (infos.size() != 0) {
                            infos.clear();
                        }
                        infos.addAll(list.getLightList());
                        exListView.setPullLoadEnable(false);
                        adapter.notifyDataSetChanged();
                        customStatusListView.showExListView();
                    }
                }
            }
        } else {
            if (infos.size() != 0) {
                if (infos.size() < 10) {
                    exListView.setPullLoadEnable(false);
                }
                adapter.notifyDataSetChanged();
                customStatusListView.showExListView();
            } else {
                customStatusListView.showNoData("暂无数据", "重试", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        customStatusListView.showLoading();
                        onRefresh();
                    }
                });
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.discover_group_sayhi_btn:
                doGroupSayHi();
                break;
        }
    }

    Map<Integer, Long> onclickData = null;

    private void doGroupSayHi() {
        if (!ModuleMgr.getCenterMgr().getMyInfo().isVip()) {
            UIShow.showGoodsVipBottomDlg(getContext());
            return;
        }

        if (isHasNoSayHi()) {
            if (ModuleMgr.getCenterMgr().isCanGroupSayHi(getActivity())) {
                LoadingDialog.show(getActivity());
                handler.sendEmptyMessage(Group_sayHai_Msg);
            }
        } else {
            PToast.showShort(getString(R.string.say_hi_group_refresh));
        }
    }

    /**
     * 一键打招呼
     */
    private void doSayHi() {
        Iterator<UserLight> userInfos = infos.iterator();
        while (userInfos.hasNext()) {
            final UserLight infoLight = userInfos.next();
//            if (!infoLight.isSayHello()) {
//                ModuleMgr.getChatMgr().sendSayHelloMsg(String.valueOf(infoLight.getUid()), getString(R.string.say_hello_txt),
//                        infoLight.getKf_id(),
//                        ModuleMgr.getCenterMgr().isRobot(infoLight.getKf_id()) ?
//                                Constant.SAY_HELLO_TYPE_NEAR : Constant.SAY_HELLO_TYPE_SIMPLE, null);
//                notifyAdapter(infoLight.getUid());
//                handler.sendEmptyMessage(Group_sayHai_Msg);
//                break;
//            }
        }

        if (!isHasNoSayHi()) {
            LoadingDialog.closeLoadingDialog();
        }
    }

    /**
     * 刷新打招呼的状态
     *
     * @param uid
     */
    private void notifyAdapter(long uid) {
        for (UserLight info : infos) {
            if (info.getUid() == uid) {
//                info.setSayHello(true);
                adapter.notifyDataSetChanged();
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Group_sayHai_Msg:
                    doSayHi();
                    break;
            }
        }
    };

    /**
     * 当前列表内有没有还未打招呼的人
     *
     * @return true有 false没有
     */
    private boolean isHasNoSayHi() {
        if (infos.size() != 0) {
            for (UserLight info : infos) {
//                if (!info.isSayHello()) {
//                    return true;
//                }
            }
            return false;
        } else {
            return false;
        }
    }

    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_Say_Hello_Notice: //一键打招呼完成后 当前列表内有一键打招呼的人的数据的时候 更新列表
                List<UserInfoLightweight> data = (List<UserInfoLightweight>) value;
                for (int i = 0; i < data.size(); i++) {
                    notifyAdapter(data.get(i).getUid());
                }
                break;
            case MsgType.MT_Say_HI_Notice:
                long uid = (long) value;
                notifyAdapter(uid);
                break;
            default:
                break;
        }
    }

    /**
     * 是否显示群打招呼
     *
     * @param isCanShow 状态更新是否显示（该参数控制在数据未加载的时候 不显示群打招呼） 默认传false
     */
    private void setGroupSayhiBtn(boolean isCanShow) {
        //我是VIP的时候不显示
        if (ModuleMgr.getCenterMgr().getMyInfo().isVip() || !ModuleMgr.getCenterMgr().getMyInfo().isMan()) {
            groupSayhiBtn.setVisibility(View.GONE);
        } else {  //非VIP附近的人显示
            groupSayhiBtn.setVisibility(View.GONE);
        }
    }

    /**
     * 刷新首页
     */
    public void refreshList() {
        onRefresh();
        if (adapter != null && adapter.getList() != null && adapter.getList().size() != 0) {
            exListView.setSelection(0);
        }
    }
}
